package com.nhjf.admin.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import com.nhjf.common.util.LogMessage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图片缩放
 * @author Administrator
 *
 */
public class PictureUtil {

	/**
	 * 缩放
	 * 
	 * @param srcFilePath
	 *            源图片路径
	 * @param descFilePath
	 * 			  目标图片路径
	 * @param height
	 *            高度
	 * @param width
	 *            宽度
	 * @param bb
	 *            比例不对时是否需要补白
	 */
	public static void resize(String srcFilePath,String descFilePath, int height, int width, boolean bb) {
		
		try {
			double ratio = 0.0; // 缩放比例
			File f = new File(srcFilePath);
			BufferedImage bi = ImageIO.read(f);
			Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
			// 计算比例
			if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
				if (bi.getHeight() > bi.getWidth()) {
					ratio = (new Integer(height)).doubleValue()
							/ bi.getHeight();
				} else {
					ratio = (new Integer(width)).doubleValue() / bi.getWidth();
				}
				AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
				itemp = op.filter(bi, null);
			}
			if (bb) {
				BufferedImage image = new BufferedImage(width, height,
						BufferedImage.TYPE_INT_RGB);
				Graphics2D g = image.createGraphics();
				g.setColor(Color.white);
				g.fillRect(0, 0, width, height);
				if (width == itemp.getWidth(null)) {
					g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
				} else {
					g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
				}
				g.dispose();
				itemp = image;
			}
			ImageIO.write((BufferedImage) itemp, "jpg",new File(descFilePath));
		} catch (IOException e) {
			LogMessage.logwrite(PictureUtil.class, e.getMessage());
		}
	}
	
	/**
	 * 删除图片文件夹
	 * @param f
	 * @return
	 */
	public boolean deletedir(File f) {
		if (f.isDirectory()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()){
					deletedir(files[i]);
				}else{
					deletefile(files[i]);
				}
			}
		}
		f.delete();
		return true;

	}

	private boolean deletefile(File f) {
		if (f.isFile()) {
			f.delete();
		}
		return true;
	}
	
	/**
	 * 图片缩放
	 * @param imgsrc 源文件路径
	 * @param imgdist 目标文件路径
	 * @param widthdist 目标文件宽度
	 * @param heightdist 目标文件高度
	 */
	public static void zoomImage(String imgsrc, String imgdist, int widthdist,int heightdist) {
		try {
			File srcfile = new File(imgsrc);
			if (!srcfile.exists()) {
				
				return;
			}
			Image src = javax.imageio.ImageIO.read(srcfile);

			if (heightdist > src.getHeight(null)) {
				heightdist = src.getHeight(null);
			}
			if (widthdist > src.getWidth(null)) {
				widthdist = src.getWidth(null);
			}

			BufferedImage tag = new BufferedImage((int) widthdist,(int) heightdist, BufferedImage.TYPE_INT_RGB);

			tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist,Image.SCALE_SMOOTH), 0, 0, null);

			String dddd = imgdist.substring(0, imgdist.lastIndexOf(File.separator));
			File d = new File(dddd);
			if (!d.isDirectory()) {
				d.mkdirs();
			}
			FileOutputStream out = new FileOutputStream(imgdist);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag);
			out.close();
			
		
		} catch (Exception e) {
			
			LogMessage.logwrite(PictureUtil.class, e.getMessage());
		}
	}
	
	
	/**
	 * 定位剪切图
	 * @param filePath
	 * @param w
	 * @param h
	 * @param x
	 * @param y
	 * @param imW
	 * @param imH
	 * @param destPath
	 */
	public static void cutImage(String filePath, int w, int h, int x, int y,
			int imW, int imH, String destPath) {
		try {
			BufferedImage bi = ImageIO.read(new File(filePath));
			int sw = bi.getWidth();
			int sh = bi.getHeight();
			if (sw > sh&&sw>imW) {
				if (sw > imW) {
					sh = sh / (sw / imW);
					sw = imW;
					
				}
			} else if (sw <sh &&sh>imH){
				if (sh > imH) {
					sw = sw / (sh / imH);
					sh = imH;
					
				}
			}
		
		
			Image img;
			ImageFilter cropFilter;
			if (sw >= w && sh >= h) {
				Image image = bi.getScaledInstance(sw, sh, Image.SCALE_DEFAULT);
				cropFilter = new CropImageFilter(x, y, w, h);
				img = Toolkit.getDefaultToolkit().createImage(
						new FilteredImageSource(image.getSource(), cropFilter));

				BufferedImage tag = new BufferedImage(w, h,
						BufferedImage.TYPE_INT_RGB);
				OutputStream out = new FileOutputStream(new File(destPath));
				Graphics g = tag.getGraphics();
				g.drawImage(img, 0, 0, null); // 绘制缩小后的图
				g.dispose();
				// 输出为文件
				ImageIO.write(tag, "JPEG", out);
				out.flush();
				out.close();
			}
			
		} catch (Exception e) {
			LogMessage.logwrite(PictureUtil.class, e.getMessage());
		}
	}
	
	/**
	 * 成比例缩小图
	 * @param filePath
	 * @param imW
	 * @param imH
	 * @param destPath
	 */
	public static void deflateImage(String filePath,
			int imW, int imH, String destPath) {
		try {
			 int w=0;
			 int h=0;
			 int x=0;
			 int y=0;
			BufferedImage bi = ImageIO.read(new File(filePath));
			int sw = bi.getWidth();
			int sh = bi.getHeight();
			if (sw > sh&&sw>imW) {
				    sh = sh / (sw / imW);
					sw = imW;
			} else if (sw < sh &&sh>imH){
				   sw = sw / (sh / imH);
				   sh = imH;
			}else if(sw == sh&&sh>imH&&sw>imW){
				   int flag=sh / (sw / imW);
				   sh = flag ;
//				   sw = sw / (sh / imH);
				   sw = flag;
			}
			w=sw;
			h=sh;
			Image img;
			ImageFilter cropFilter;
			if (sw >= w && sh >= h) {
				Image image = bi.getScaledInstance(sw, sh, Image.SCALE_DEFAULT);
				cropFilter = new CropImageFilter(x, y, w, h);
				img = Toolkit.getDefaultToolkit().createImage(
						new FilteredImageSource(image.getSource(), cropFilter));

				BufferedImage tag = new BufferedImage(w, h,
						BufferedImage.TYPE_INT_RGB);
				OutputStream out = new FileOutputStream(new File(destPath));
				Graphics g = tag.getGraphics();
				g.drawImage(img, 0, 0, null); // 绘制缩小后的图
				g.dispose();
				// 输出为文件
				ImageIO.write(tag, "JPEG", out);
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			LogMessage.logwrite(PictureUtil.class, e.getMessage());
		}
	}
	
	
	/**
	 * 复制文件
	 * @param filePath
	 * @param destPath
	 */
	public static void copyFile(String filePath , String destPath) {
		File srcFile = new File(filePath);
		File destFile = new File(destPath);
        if(!destFile.getParentFile().exists()){
            System.out.println("父文件夹不存在，创建之");
            destFile.getParentFile().mkdirs();
        }
		FileInputStream input = null;
		FileOutputStream output = null; 
		try {
			  input = new FileInputStream(srcFile);
			  output = new FileOutputStream(destFile);
			  byte[] buffer = new byte[4096];
              int n = 0;
              while (-1 != (n = input.read(buffer))) {
				      output.write(buffer, 0, n);
			  }
		} catch (FileNotFoundException e) {
			LogMessage.logwrite(PictureUtil.class, e.getMessage());
		}catch (IOException e) {
			LogMessage.logwrite(PictureUtil.class, e.getMessage());
		} finally {
			 try {
            	   if (output != null) {
                        output.close();
					}
                    if (input != null) {
                        input.close();
                    }
			 } catch (IOException e) {
				 LogMessage.logwrite(PictureUtil.class, e.getMessage());
		    }      
               
         }
	} 
	
	/**
	 * 
	 * @方法功能说明：裁剪上传图片至规定大小
	 * @修改者名字：luoyun
	 * @修改时间：2015年4月23日上午9:35:24
	 * @修改内容：
	 * @参数：@param filePath 源图片路径
	 * @参数：@param destPath 处理后图片路径
	 * @参数：@param destWidth 图片规定宽度
	 * @参数：@param destHeight 图片规定高度
	 * @return:void
	 * @throws
	 */
	public static void handlerImageSize(String filePath , String destPath,int destWidth,int destHeight){
		
		try {
			BufferedImage sourceImage = ImageIO.read(new File(filePath));
			int imageWidth = sourceImage.getWidth();
			int imageHeight = sourceImage.getHeight();
			
			//图片宽和高都小于规定尺寸，不处理
			if(imageWidth <= destWidth && imageHeight <= destHeight){
				return ;
			}
			
			//图片宽和高都大于规定尺寸，将图片较短的一边等比例压缩到系统规定尺寸，然后以图片中心为原点，舍弃超出系统设定比例的图片部分
			if(imageWidth > destWidth && imageHeight > destHeight){
				//计算目标图片长宽
				int width = 0;
				int height = 0;
				if(imageWidth < imageHeight){ //图片宽边为短边，压缩图片宽边长度为规定长度，长边长度按宽边压缩的比例压缩
					//缩小比例
					double scale = (double)destWidth / (double)imageWidth ; 
					height = (int)(scale * imageHeight);
					width = destWidth;
				}else if(imageWidth ==  imageHeight){ //图片长宽相等，长宽都为规定长宽
					width = destWidth;
					height = destHeight;
				}else if(imageWidth > imageHeight){
					//缩小比例
					double scale = (double)destHeight / (double)imageHeight;
					width = (int)(scale * imageWidth);
					height = destHeight;
				}
				
				//绘制压缩后的图片
				Image image = sourceImage.getScaledInstance(width, height, Image.SCALE_DEFAULT);
				ImageFilter cropFilter;
				cropFilter = new CropImageFilter(0, 0, width, height);
				Image tempImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
				BufferedImage tag = new BufferedImage(width, height ,BufferedImage.TYPE_INT_RGB);
				OutputStream out = new FileOutputStream(new File("d:/2.jpg"));
				Graphics g = tag.getGraphics();
				g.drawImage(tempImage, 0, 0, null); 
				g.dispose();
				ImageIO.write(tag, "JPEG", out);
				out.flush();
				out.close();
				
				//以图片中心为原点，舍弃超出系统设定比例的图片部分
				image = tempImage.getScaledInstance(destWidth, destHeight, Image.SCALE_DEFAULT);
				cropFilter = new CropImageFilter(0, 0, destWidth, destHeight);
				Image destImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
				tag = new BufferedImage(destWidth, destHeight ,BufferedImage.TYPE_INT_RGB);
				out = new FileOutputStream(new File("d:/3.jpg"));
				g = tag.getGraphics();
				//计算裁剪的坐标
				
				int x = (width - destWidth)/2;
				int y = (height - destHeight)/2;
				
				int x1 = destWidth - x;
				int y1 = destHeight - y;
				
				g.drawImage(destImage, 0, 0, destWidth, destHeight, x, y, x1, y1, null);
				g.dispose();
				ImageIO.write(tag, "JPEG", out);
				out.flush();
				out.close();
				
			}
			
			//图片宽和高一个大于规定尺寸，一个小于规定尺寸；以图片中心为原点，舍弃超出系统设定比例的图片部分
			if((imageWidth > destWidth && imageHeight < destHeight) || (imageWidth < destWidth && imageHeight > destHeight)){
				
				if(imageHeight < destHeight){
					destHeight = imageHeight;
				}
				
				if(imageWidth < destWidth){
					destWidth = imageWidth;
				}
				
				Image image = sourceImage.getScaledInstance(destWidth, destHeight, Image.SCALE_DEFAULT);
				CropImageFilter cropFilter = new CropImageFilter(0, 0, destWidth, destHeight);
				Image destImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
				BufferedImage tag = new BufferedImage(destWidth, destHeight ,BufferedImage.TYPE_INT_RGB);
				OutputStream out = new FileOutputStream(new File("d:/3.jpg"));
				Graphics g = tag.getGraphics();
				//计算裁剪的坐标
				
				int x = (imageWidth - destWidth)/2;
				int y = (imageHeight - destHeight)/2;
				
				int x1 = imageWidth - x;
				int y1 = imageHeight - y;
				
				g.drawImage(destImage, 0, 0, destWidth, destHeight, x, y, x1, y1, null);
				g.dispose();
				ImageIO.write(tag, "JPEG", out);
				out.flush();
				out.close();
				
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
          
	
	public static void main(String args[]){
		PictureUtil.handlerImageSize("d:/1.jpg", "d:/3.jpg", 512, 600);
		System.err.println("finish");
	}
               
        


	
}
